﻿package de.gameduell.framework.facebook.app{
	import de.gameduell.framework.facebook.app.appevents.CoinEvent;
	import de.gameduell.framework.facebook.app.popups.BuyCashPopup;
	import de.gameduell.framework.facebook.app.popups.BuyLifeForCashPopup;
	import de.gameduell.framework.facebook.app.popups.ErrorPopup;
	import de.gameduell.framework.facebook.app.popups.GameFlowMessagePopup;
	import de.gameduell.framework.facebook.app.popups.HighscorePopup;
	import de.gameduell.framework.facebook.app.popups.InterstitialPopup;
	import de.gameduell.framework.facebook.app.popups.NewUserPopup;
	import de.gameduell.framework.facebook.app.popups.NoLivesPopup;
	import de.gameduell.framework.facebook.app.popups.PyramidBasePopup;
	import de.gameduell.framework.facebook.app.popups.UnlockMoreLivesPopup;

	import de.gameduell.framework.application.Window;
	import de.gameduell.framework.debug.Debug;
	import de.gameduell.framework.facebook.FBBaseAppLayout;
	import de.gameduell.framework.facebook.FBBaseController;
	import de.gameduell.framework.facebook.FBBaseGameState;
	import de.gameduell.framework.facebook.event.CommunicationErrorEvent;
	import de.gameduell.framework.facebook.event.DonationEvent;
	import de.gameduell.framework.locale.LocaleData;
	import de.gameduell.framework.queue.DelayAction;
	import de.gameduell.framework.queue.PopupAction;
	import de.gameduell.framework.util.Library;

	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.net.SharedObject;

	public class View {
		
		protected var content:Sprite;
		protected var window:Window;
		protected var splitTestConfig:SplittestConfig;
		protected var library:Library;
		protected var controller:Controller;
		protected var pageManager:PageManager;
		protected var localeData:LocaleData;
		protected var cookie:SharedObject;
		protected var errorPopup:ErrorPopup;
		
		public function View(aWindow:Window){
			splitTestConfig = SplittestConfig.getInstance();
			window  = aWindow;
			content = window.getContent();
			library = Library.getInstance();
			localeData = LocaleData.getInstance();
		
			initMainView();
			
			controller  = Controller.getInstance();
			controller.addEventListener(CommunicationErrorEvent.COMMUNICATION_ERROR, onServerError);
			controller.addEventListener(FBBaseController.OUT_OF_LIVES, onOutOfLives);
			controller.addEventListener(FBBaseController.OUT_OF_MONEY, onOutOfMoney);
			controller.addEventListener(FBBaseController.TUTORIAL_FINISHED, onTutorialFinished);
			controller.gameState.addEventListener(FBBaseGameState.FIRST_TIME_START, onNewUser);
			controller.gameData.addEventListener(GameData.APP_MAX_LIVES_CHANGED, onMaxLivesChanged);
			controller.addEventListener(FBBaseController.NEW_HIGHSCORE, onNewHighscore);
			controller.coinEventManager.addEventListener(CoinEvent.COIN_EVENT_STARTED, onCoinTriggeredAction);
			controller.gameData.addEventListener(DonationEvent.DONATION_FROM_BUDDIES, onBuddyDonation);
			controller.gameData.addEventListener(GameData.APP_THANKS_FOR_DONATION, onThanksForDonation);
			
			cookie = SharedObject.getLocal(controller.trackingName + "_app");
			checkUserCookies();
			
			pageManager = PageManager.getInstance();
			pageManager.init(content);
		}

		private function onThanksForDonation(event:Event):void {
			try{
				var donationReceiver:String = controller.gameData.donationReceiver;
				localeData.setValue("donationReceiverName", controller.facebookData.getFriendProfileByID(donationReceiver).firstName);
				var donationPopup:PyramidBasePopup = new PyramidBasePopup("generic_1_button_header_content", "thanksForDonation", 0, true);
				donationPopup.registerButton("okButton", donationPopup.hide);
				new PopupAction(donationPopup, true, "thanksForDonation");
			}catch(e:Error){
				Debug.trace("View::onThanksForDonation: friend profile not in list: donationReceiver" + donationReceiver, Debug.WARNING);
			}
		}

		private function onBuddyDonation(event:DonationEvent):void {
			localeData.setValue("donationType", event.donationType);
			localeData.setValue("donationValue", event.donationValue);
			if(event.donationType == "lives" && event.donationValue == "1"){
				localeData.setValue("donationType", "1_life");
			}
			var donationPopup:PyramidBasePopup = new PyramidBasePopup("generic_1_button_header_content", "donationPopup", 0, true);
			donationPopup.registerButton("okButton", donationPopup.hide);
			new PopupAction(donationPopup, true, "donationPopup");
		}

		private function onCoinTriggeredAction(event:CoinEvent):void {
			Debug.trace("View::onCoinEvent: " + event.coinTriggeredAction.eventName, Debug.WARNING);
			var interstitialPopup:InterstitialPopup = new InterstitialPopup(event.coinTriggeredAction.eventName);
			new PopupAction(interstitialPopup, true);
		}
		
		private function onNewHighscore(event:Event):void {
			new PopupAction(new HighscorePopup(), true, "newHighscorePopup");
		}

		private function onMaxLivesChanged(event:Event):void {
			new PopupAction(new UnlockMoreLivesPopup(), true);
		}

		private function onTutorialFinished(event:Event = null):void {
			if(controller.gameState.isFirstTimeUser && controller.gameData.coins < 20){
				localeData.setValue("tutorialCoinsNeeded", String(controller.gameData.pyramid.currentBrick.coinsNeeded));
				var myPopup:GameFlowMessagePopup = new GameFlowMessagePopup("tutorialFinishedPopup", 8000);
				myPopup.position = new Point(375,360);
				myPopup.show();
			}
		}
		
		private function onNewUser(event:Event):void {
			new PopupAction(new NewUserPopup(), true, "NewUserPopup");
		}
		
		private function onOutOfLives(event:Event = null):void {
			Debug.trace("View::onOutOfLives: " + splitTestConfig.requestLifeEnabled);
			if(splitTestConfig.requestLifeEnabled){
				new PopupAction(new NoLivesPopup(), true, "NoLivesPopup");
				new DelayAction(2500, true);
			}
			try{
				var price:int = controller.catalog.getItemByTitle("DRG_LIFE").price;
				
				Debug.trace("View::onOutOfLives: LIFE price: " + price, Debug.DEBUG);
				
				if(int(controller.applicationData.facebookData.balance.balance) < price){
					localeData.setValue("buyCashFor", "lives");
					new PopupAction(new BuyCashPopup(), true, "BuyCashPopup");
				}else{
					new PopupAction(new BuyLifeForCashPopup(), true, "BuyLifeForCashPopup");
				}
			}catch(e:Error){
				Debug.trace("View::onNewUser: " + e.getStackTrace() , Debug.ERROR);
				new PopupAction(new BuyCashPopup(), true, "BuyCashPopup");
			}
		}
		
		private function onOutOfMoney(event:Event):void {
			localeData.setValue("buyCashFor", "default");
			new PopupAction(new BuyCashPopup(), true, "BuyCashPopup");
		}

		private function checkUserCookies():void {
			// TODO - add settings here
		}
		
		private function onServerError(event:Event):void {
			localeData.setValue("errorReason", CommunicationErrorEvent(event).error);
			if(errorPopup == null){
				errorPopup = new ErrorPopup("serverError");
			}else{
				errorPopup.show();
			}
		}

		private function initMainView():void {
			var mainBG:Sprite = library.createSprite("main_background");
			mainBG.x = FBBaseAppLayout.getInstance().contentPosition.x;
			mainBG.y = FBBaseAppLayout.getInstance().contentPosition.y;
			content.addChild(mainBG);
		}
		
//		public function checkAllPopups(event:Event = null):void {
//			var aResult:GameResult = controller.lastGameResult;
//			aResult = new GameResult("1000,1,2,3", "1");

//			new PopupAction(new InterstitialPopup("get_friends_interstitial_01"), true);
//			new PopupAction(new InterstitialPopup("gd_interstitial_01"), true);
//			new PopupAction(new InterstitialPopup("gd_interstitial_02"), true);
//			new PopupAction(new InterstitialPopup("hurz"), true);
//			new PopupAction(new UnlockMoreLivesPopup(), true);
//			new PopupAction(new NoLivesPopup(), true);
//			new PopupAction(new AlertPopup("alertPopup", 5000, true), true, "AlertPopup");
//			new PopupAction(new BuyCashPopup(), true, "BuyCashPopup");
//			new PopupAction(new BuyLifeForCashPopup(), true, "BuyLifeForCashPopup");
//			new PopupAction(new ErrorPopup("serverError"), true, "ErrorPopup");

//			new PopupAction(new GameFlowMessagePopup("tutorialFinishedPopup", 10000), true, "GameFlowMessagePopup");
//			new PopupAction(new ShareLevelUpPopup(controller.gameData.pyramid.currentBrick), true, "ShareLevelUpPopup");
//			new PopupAction(new SelectBrickPoup(controller.gameData.pyramid.currentBrick), true, "UnlockMoreLivesPopup");
//			new PopupAction(new CoinsCollectedPopup(new Point(0,0)), true, "CoinsCollectedPopup");
//			new PopupAction(new NewUserPopup(), true, "NewUserPopup");
//			new PopupAction(new HighscorePopup(), true, "HighscorePopup");
//			new PopupAction(new InterstitialPopup("get_friends_interstitial_01"), true, "InterstitialPopup");
//			new PopupAction(new LevelUpPopup(controller.gameData.pyramid.currentBrick), true, "LevelUpPopup");
//		}
	}
}